/*   Valhalla MailChecker -- Simple IMAP Mail Checker
*    Copyright (C) 2010-2011  Guillaume Florimond (gflorimond at gmail dot com)
*
*    This program is free software: you can redistribute it and/or modify
*    it under the terms of the GNU General Public License as published by
*    the Free Software Foundation, either version 3 of the License, or
*    any later version.
*
*    This program is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*    GNU General Public License for more details.
*
*    You should have received a copy of the GNU General Public License
*    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

/*
 * AccountConfigFrame.java
 *
 * Created on 21 mai 2010, 19:42:16
 */

package fr.valhalla.mailcheck.gui;

import fr.valhalla.mailcheck.gui.classic.AccountList;
import fr.valhalla.mailcheck.Account;
import fr.valhalla.mailcheck.Checker;
import fr.valhalla.mailcheck.utils.NiceColors;
import fr.valhalla.mailcheck.utils.SoundPlayer;
import java.util.Iterator;
import javax.swing.JOptionPane;

/**
 *
 * @author gf
 */
public class AccountConfigFrame extends javax.swing.JFrame {

    private boolean newAccount; // bouton enregistrer crée un nouveau compte ou met à jour un compte existant?
    private AccountList parent;

    /** Creates new form AccountConfigFrame */
    public AccountConfigFrame() {
        initComponents();
        initSound();
        newAccount = true;
        portField.setText("993");
        SSLCheckBox.setSelected(true);
        accountNameField.setText("Nouveau compte");
        folderField.setText("Inbox");
        changesLabel.setText("");
        pack();
    }

    public AccountConfigFrame(Account ac) {
        initComponents();
        initSound();
        newAccount = false;
        accountNameField.setText(ac.getAccountName());
        accountNameField.setEditable(false);
        loginField.setText(ac.getLogin());
        passwordField.setText(ac.getPassword());
        hostField.setText(ac.getHost());
        folderField.setText(ac.getFolder());
        portField.setText(new Integer(ac.getPort()).toString());
        setSleep(new Integer(ac.getSleep()));
        if(ac.isSSL()) SSLCheckBox.setSelected(true); else SSLCheckBox.setSelected(false);
        changesLabel.setText("Les changements seront pris en compte au prochain redémarrage.");
        if(ac.hasNotifications()) notificationsCheckBox.setSelected(true); else notificationsCheckBox.setSelected(false);
        pack();
    }

    public AccountConfigFrame(Account ac, AccountList parent) {
        this(ac); // appel d'un autre constructeur
        this.parent = parent;
    }

    public AccountConfigFrame(AccountList parent) {
        this();
        this.parent = parent;
    }

    private void initSound() {
        soundCombo.addItem("Aucun");
        try {
            SoundPlayer sp = new SoundPlayer();
            Iterator i = sp.SOUNDS.keySet().iterator();
            while(i.hasNext()) {
                soundCombo.addItem(i.next());
            }
        } catch(Exception e) {e.printStackTrace();}
    }

    private String getSound() {
        if(soundCombo.getSelectedIndex() == 0)
            return "NONE";

        try {
            SoundPlayer sp = new SoundPlayer();
            return sp.SOUNDS.get(soundCombo.getSelectedItem().toString());
        } catch(Exception e) {e.printStackTrace();}

        return "NONE";
    }

    private int getSleep() {
        int sleep = new Integer(sleepField.getText());
        int multiplier;
        switch(sleepCombo.getSelectedIndex()) {
            case 0: multiplier = 1; break;
            case 1: multiplier = 60; break;
            case 2: multiplier = 3600; break;
            default: multiplier = 1; break;
        }
        return sleep * multiplier;
    }

    private void setSleep(int sleep) {
        // heures
        if(sleep > 3600 && sleep % 3600 == 0) {
            sleepCombo.setSelectedIndex(2);
            sleepField.setText(new Integer(sleep / 3600).toString());
        // minutes
        } else if(sleep > 60 && sleep % 60 == 0) {
            sleepCombo.setSelectedIndex(1);
            sleepField.setText(new Integer(sleep / 60).toString());
        // secondes
        } else {
            sleepCombo.setSelectedIndex(0);
            sleepField.setText(new Integer(sleep).toString());
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        accountNameField = new javax.swing.JTextField();
        hostField = new javax.swing.JTextField();
        loginField = new javax.swing.JTextField();
        passwordField = new javax.swing.JTextField();
        portField = new javax.swing.JTextField();
        SSLCheckBox = new javax.swing.JCheckBox();
        jLabel7 = new javax.swing.JLabel();
        sleepField = new javax.swing.JTextField();
        saveButton = new javax.swing.JButton();
        deleteButton = new javax.swing.JButton();
        jLabel9 = new javax.swing.JLabel();
        folderField = new javax.swing.JTextField();
        sleepCombo = new javax.swing.JComboBox();
        changesLabel = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        soundCombo = new javax.swing.JComboBox();
        playSoundLabel = new javax.swing.JLabel();
        notificationsCheckBox = new javax.swing.JCheckBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Candara", 0, 18));
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Configuration du compte");

        jLabel2.setText("Nom du compte");

        jLabel3.setText("Adresse du serveur");

        jLabel4.setText("Nom d'utilisateur");

        jLabel5.setText("Mot de passe");

        jLabel6.setText("Port");

        SSLCheckBox.setText("SSL");
        SSLCheckBox.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                SSLCheckBoxStateChanged(evt);
            }
        });

        jLabel7.setText("Vérifier toutes les");

        saveButton.setText("Enregistrer");
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        deleteButton.setText("Supprimer");
        deleteButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteButtonActionPerformed(evt);
            }
        });

        jLabel9.setText("Dossier");

        sleepCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "secondes", "minutes", "heures" }));
        sleepCombo.setSelectedIndex(1);

        changesLabel.setForeground(NiceColors.SALMON);
        changesLabel.setText("[Changes Label]");

        jLabel8.setText("Son \"nouveau message\"");

        playSoundLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/fr/valhalla/mailcheck/resources/images/control_play.png"))); // NOI18N
        playSoundLabel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                playSoundLabelMouseClicked(evt);
            }
        });

        notificationsCheckBox.setSelected(true);
        notificationsCheckBox.setText("Afficher les notifications");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 495, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel9)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel6)
                        .addComponent(jLabel5))
                    .addComponent(jLabel4)
                    .addComponent(jLabel2)
                    .addComponent(jLabel7)
                    .addComponent(jLabel8))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(notificationsCheckBox)
                    .addComponent(hostField, javax.swing.GroupLayout.DEFAULT_SIZE, 292, Short.MAX_VALUE)
                    .addComponent(accountNameField, javax.swing.GroupLayout.DEFAULT_SIZE, 292, Short.MAX_VALUE)
                    .addComponent(loginField, javax.swing.GroupLayout.DEFAULT_SIZE, 292, Short.MAX_VALUE)
                    .addComponent(passwordField, javax.swing.GroupLayout.DEFAULT_SIZE, 292, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(portField)
                            .addComponent(sleepField, javax.swing.GroupLayout.DEFAULT_SIZE, 55, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(SSLCheckBox)
                            .addComponent(sleepCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(folderField, javax.swing.GroupLayout.DEFAULT_SIZE, 292, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(soundCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(playSoundLabel)))
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(64, 64, 64)
                .addComponent(deleteButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(changesLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 292, Short.MAX_VALUE)
                    .addComponent(saveButton, javax.swing.GroupLayout.DEFAULT_SIZE, 292, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(20, Short.MAX_VALUE)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(accountNameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(hostField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(loginField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(passwordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel9)
                    .addComponent(folderField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(portField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(SSLCheckBox)
                    .addComponent(jLabel6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(sleepField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(sleepCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(playSoundLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(soundCombo)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel8)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(notificationsCheckBox)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(saveButton)
                    .addComponent(deleteButton))
                .addGap(1, 1, 1)
                .addComponent(changesLabel))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        // Get master password
        String masterpassword = (String) JOptionPane.showInputDialog(
                this,
                "Entrez un mot de passe afin de \nsécuriser votre compte:",
                "Master Password",
                JOptionPane.QUESTION_MESSAGE,
                null,
                null,
                "");

        //Crypt data with master password
        if ((masterpassword != null) && (masterpassword.length() > 0)) {
            Account ac = new Account(masterpassword);
            if(newAccount == true) {
                ac.addAccount(accountNameField.getText(),
                        loginField.getText(),
                        passwordField.getText(),
                        "imap",
                        hostField.getText(),
                        folderField.getText(),
                        new Integer(portField.getText()),
                        getSleep(),
                        new Boolean(SSLCheckBox.isSelected()),
                        getSound(),
                        new Boolean(notificationsCheckBox.isSelected()));
                 Checker c = new Checker(new Account(accountNameField.getText(),masterpassword),parent.getKernel());
                 parent.getContentPane().add(c.getCheckPanel());
                 c.start();
                 parent.pack();
            } else {
                ac.updateAccount(accountNameField.getText(),
                        loginField.getText(),
                        passwordField.getText(),
                        "imap",
                        hostField.getText(),
                        folderField.getText(),
                        new Integer(portField.getText()),
                        getSleep(),
                        new Boolean(SSLCheckBox.isSelected()),
                        getSound(),
                        new Boolean(notificationsCheckBox.isSelected()));
            }
            this.dispose();
        }
    }//GEN-LAST:event_saveButtonActionPerformed

    private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed
        String masterpassword = (String) JOptionPane.showInputDialog(
                this,
                "Entrez le mot de passe global pour confirmer la suppression du compte\nATTENTION : la suppression est définitive !",
                "Master Password",
                JOptionPane.WARNING_MESSAGE,
                null,
                null,
                "");

        if ((masterpassword != null) && (masterpassword.length() > 0)) {
            Account ac = new Account(accountNameField.getText(),masterpassword);
            ac.deleteAccount();
            JOptionPane.showMessageDialog(this, "Compte " + accountNameField.getText() + " supprimé.\n Les changements seront effectifs au prochain redémarrage du logiciel.");
            this.dispose();
        }
    }//GEN-LAST:event_deleteButtonActionPerformed

    private void SSLCheckBoxStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_SSLCheckBoxStateChanged
        if(SSLCheckBox.isSelected()) {
            portField.setText("993");
        } else {
            portField.setText("143");
        }
    }//GEN-LAST:event_SSLCheckBoxStateChanged

    private void playSoundLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_playSoundLabelMouseClicked
        // Aucun son : retour
        if(soundCombo.getSelectedIndex() == 0)
            return;

        try {
            SoundPlayer sp = new SoundPlayer();
            String selectedSound = soundCombo.getSelectedItem().toString();
            String soundFile = sp.SOUNDS.get(selectedSound);
            sp = new SoundPlayer(soundFile);
            sp.play();
        } catch(Exception e) {e.printStackTrace();}
        
    }//GEN-LAST:event_playSoundLabelMouseClicked


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JCheckBox SSLCheckBox;
    private javax.swing.JTextField accountNameField;
    private javax.swing.JLabel changesLabel;
    private javax.swing.JButton deleteButton;
    private javax.swing.JTextField folderField;
    private javax.swing.JTextField hostField;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JTextField loginField;
    private javax.swing.JCheckBox notificationsCheckBox;
    private javax.swing.JTextField passwordField;
    private javax.swing.JLabel playSoundLabel;
    private javax.swing.JTextField portField;
    private javax.swing.JButton saveButton;
    private javax.swing.JComboBox sleepCombo;
    private javax.swing.JTextField sleepField;
    private javax.swing.JComboBox soundCombo;
    // End of variables declaration//GEN-END:variables

}
